import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.bson.Document;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Set;

public class SuccessToExcel {
    public static void main(String[] args) throws IOException {
        MongoClient mongoClient = new MongoClient("192.168.1.173",27017);
        final MongoCollection<Document> collection = mongoClient.getDatabase("企查查").getCollection("Success_List3");
        Workbook workbook = new SXSSFWorkbook(150000);
        Sheet sheet = workbook.createSheet();

        //excel行
        Row row = sheet.createRow(0);
        //int index = 0;        //row.createCell(index++).setCellValue("企业名称");

        FindIterable<Document> documents = collection.find();
        Document first_doc = documents.first();

        int index = 0;
        Set<String> key_set = first_doc.keySet();
        for (String key : key_set){
            if (key.equals("_id"))
                continue;
            row.createCell(index++).setCellValue(key);
        }
        int rownum = 1;
        int count = 0;
        for (Document document : documents) {
            int cellnum = 0;

            count++;
            Row row1 = sheet.createRow(rownum++);
            for (String key : key_set) {
                if (key.equals("_id"))
                    continue;
                row1.createCell(cellnum++).setCellValue(document.get(key).toString());
            }
           // row1.createCell(cellnum++).setCellValue(document.get("_id").toString());


            System.out.println("正在写入------------------------------");
        }

//        workbook.write(new FileOutputStream("C:\\Users\\jinghe\\192.168.1.173\\高新技术企业\\excel导出\\高新技术企业\\认定.xlsx"));
        workbook.write(new FileOutputStream("D:\\测试临时文件\\企查查成功目录.xls"));
        System.out.println("写去excel完毕*--------------------");
        System.out.println("条目数量："+count);

    }
}
